package com.mzba.place;

import java.util.HashMap;

import org.json.JSONObject;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.mzba.place.db.UserTable;
import com.mzba.place.entity.ResponseEntity;
import com.mzba.place.pusher.Pusher;
import com.mzba.place.pusher.PusherCallback;
import com.mzba.place.ui.ReportDetailActivity;
import com.mzba.place.utils.AppContext;
import com.mzba.place.utils.BasicUIEvent;
import com.mzba.place.utils.HttpUtils;
import com.mzba.place.utils.StringUtil;
import com.mzba.place.utils.UICore;
import com.mzba.place.utils.UrlConfig;
/**
 * 
 * @author 06peng
 *
 */
public class PusherService extends Service implements Callback, BasicUIEvent {
	
	private static final String LOG_TAG = "PusherService";

	private static final String PUSHER_APP_KEY = "f831d9b1c2a39a62ee6a";
	private static final String PUSHER_APP_SECRET = "35f45f0d2237921854bb";
	
	private static String PRIVATE_CHANNEL = "";
	
	private Pusher mPusher;
	
	private Handler handler;
	
	public NotificationManager	mNotifMan;
	private RefreshBroadcastReceiver receiver;
	
	private final int noti_vote_id = 0x10011;
	private final int noti_mine_comment_id = 0x10012;
	private final int noti_star_comment_id = 0x10013;
	private final int noti_caution_id = 0x10014;
	private final int connect_pusher = 0x10015;
	private final int notifications_read = 0x10016;
	ResponseEntity entity;
	
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.i(LOG_TAG, "++++++++++++++++++++++++++++++++++onStartCommand");
		UICore.getInstance().setPusherService(this);
		handler = new Handler(this);
		UserTable ut = new UserTable(this);
		int id = ut.get().getId();
		if (id != 0) {
			mNotifMan = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
			receiver = new RefreshBroadcastReceiver();
			IntentFilter filter = new IntentFilter("refresh_unread");
			registerReceiver(receiver, filter);
			
			PRIVATE_CHANNEL = "private-notify_" + id;
			Log.i(LOG_TAG, "---------private-notify+" + id);
			UICore.eventTask(this, this, connect_pusher, null);
			
		}
		super.onStartCommand(intent, flags, startId);
		return START_STICKY;
	}
	
	private void setRead(){
		UICore.eventTask(this,this, notifications_read, null);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.d(LOG_TAG, "onDestroy");
		try {
			mPusher.disconnect();
			if (receiver != null) {
				unregisterReceiver(receiver);
			}
			if (mNotifMan != null) {
				mNotifMan.cancelAll();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	

	@Override
	public boolean handleMessage(Message msg) {
		try {
			switch (msg.what) {
			case connect_pusher:
				String result = msg.obj.toString();
				if (StringUtil.isNotBlank(result)) {
					Gson gson = new Gson();
					ResponseEntity entity = gson.fromJson(result, ResponseEntity.class);
					if (entity != null) {
						if (entity.getNotify_type().equals("mine_comment")) {
							gotoMsgNotification(entity, noti_mine_comment_id, "￼￼你在" + entity.getCreated_at() + "上报的事件新增了一条评论，点击查看详情.");
						} else if (entity.getNotify_type().equals("vote")) {
							gotoMsgNotification(entity, noti_vote_id, "￼￼你在" + entity.getCreated_at() + "上报的事件得到了一个安慰，点击查看详情.");
						} else if (entity.getNotify_type().equals("star_comment")) {
							gotoMsgNotification(entity, noti_star_comment_id, "￼￼你所关注的事件新增了一条评论，点击查看详情.");
						} else if (entity.getNotify_type().equals("caution")) {
							gotoMsgNotification(entity, noti_caution_id, "￼￼你所定制的警示区域中新增了一起治安事件，点击查看详情.");
						}
					}
				}
				break;

			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	@Override
	public void execute(int mes, Object obj) {
		try {
			switch (mes) {
			case connect_pusher:
				mPusher = new Pusher(PUSHER_APP_KEY, PUSHER_APP_SECRET);
				mPusher.bindAll(new PusherCallback() {
					@Override
					public void onEvent(String eventName, JSONObject eventData, String channelName) {
						Log.d(LOG_TAG, "Received " + eventData.toString() + " for event '" + eventName + "' on channel '" + channelName + "'.");
						if (eventName.equals("notify_created")) {
							if (eventData != null) {
								Message msg = Message.obtain(handler, connect_pusher, eventData.toString());
								handler.sendMessage(msg);
							}
						}
					}
				});
				mPusher.subscribe(PRIVATE_CHANNEL);
				mPusher.connect();
//				mPusher.sendEvent(eventName, eventData, channelName);
				break;
				
			case notifications_read:
				String one_read_url = UrlConfig.notificationa_read_one+entity.getId() + "";
				HashMap<String, String> paramsMap = new HashMap<String, String>();
				paramsMap.put("auth_token", AppContext.getInstance().getAuthToken());
				String response = HttpUtils.put(PusherService.this, one_read_url, paramsMap);
				Log.d("debug", "response---===>"+response);
				if (response!=null) {
//					if (getRc(response) == 0) {
//						
//					}
				}
//				handler.sendEmptyMessage(notifications_read);
				
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("deprecation")
	public void gotoMsgNotification(ResponseEntity entity, int id, String unreadConent) {
		try {
			Notification notify = new Notification(R.drawable.logo, unreadConent, System.currentTimeMillis());
			notify.flags = Notification.FLAG_AUTO_CANCEL;
			notify.flags = Notification.FLAG_SHOW_LIGHTS;
			notify.defaults = Notification.DEFAULT_SOUND;
			Intent notificationIntent = new Intent();
			notificationIntent.putExtra("id", id);
			notificationIntent.putExtra("report_detail", entity);
			notificationIntent.setAction("refresh_unread");
			PendingIntent contentIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
			notify.setLatestEventInfo(this, "新消息提醒", "" + unreadConent, contentIntent);
			mNotifMan.notify(id, notify);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public class RefreshBroadcastReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context arg0, Intent arg1) {
			try {
				if (mNotifMan != null) {
					int id = arg1.getIntExtra("id", 0);
					switch (id) {
					case noti_vote_id:
						mNotifMan.cancel(noti_vote_id);
						break;
					case noti_mine_comment_id:
						mNotifMan.cancel(noti_mine_comment_id);
						break;
					case noti_caution_id:
						mNotifMan.cancel(noti_caution_id);
						break;
					case noti_star_comment_id:
						mNotifMan.cancel(noti_star_comment_id);
						break;
					default:
						break;
					}
					 entity = (ResponseEntity) arg1.getSerializableExtra("report_detail");
					if (entity != null) {
						setRead();
						Intent intent = new Intent(PusherService.this, ReportDetailActivity.class);
						intent.putExtra("report_detail", entity.getReport());
						intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
						startActivity(intent);
					} 
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
